package com.gm.baseplatform.core.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.LogFactory;


/**
 * 
 * @author wangguomei
 * @mail e.wanggm@gmail.com
 * 
 */
public final class AjaxHelper {
	
	
	private HttpServletResponse response;
	
	public AjaxHelper(HttpServletResponse response){
		this.response = response;
	}
	
	
	public final String outTXT(String txt) {
		return this.outTXT(txt, null);
	}
	
	
	public final String outTXT(String txt, String ret) {
		try {
			this.response.setHeader("Pragma", "no-cache");
			this.response.setHeader("Cache-Control", "no-cache");
			this.response.setDateHeader("Expires", 0);
			this.response.setContentType("text/plain;charset=utf-8");
		} finally {
			this.outSTR(txt);
		}
		return ret;
	}
	
	
	public final String outHTM(String htm) {
		return this.outHTM(htm, null);
	}
	
	
	public final String outHTM(String htm, String ret) {
		try {
			this.response.setHeader("Pragma", "no-cache");
			this.response.setHeader("Cache-Control", "no-cache");
			this.response.setDateHeader("Expires", 0);
			this.response.setContentType("text/html;charset=utf-8");
		} finally {
			this.outSTR(htm);
		}
		return ret;
	}
	
	
	public final String outXML(String xml) {
		return this.outXML(xml, null);
	}
	
	
	public final String outXML(String xml, String ret) {
		try {
			this.response.setHeader("Pragma", "no-cache");
			this.response.setHeader("Cache-Control", "no-cache");
			this.response.setDateHeader("Expires", 0);
			this.response.setContentType("application/xml;charset=utf-8");
		} finally {
			this.outSTR(xml);
		}
		return ret;
	}
	
	
	public final String outJSN(String jsn) {
		return this.outJSN(jsn, null);
	}
	
	
	public final String outJSN(String jsn, String ret) {
		try {
			this.response.setHeader("Pragma", "no-cache");
			this.response.setHeader("Cache-Control", "no-cache");
			this.response.setDateHeader("Expires", 0);
			this.response.setContentType("text/plain;charset=utf-8");
		} finally {
			this.outSTR(jsn);
		}
		return ret;
	}
	
	
	private final void outSTR(String str) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if (out != null) {
			   out.write(str);
			}
		} catch (IOException e) {
			LogFactory.getLog(this.getClass()).error("AjaxResponseUtil outSTR error,", e);
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}
}
